using UnityEngine;
using Gj.Network;
using Gj.Galaxy.Network;

namespace Gj.Examples
{
    /// <summary>
    /// 网络状态检测使用示例
    /// 展示如何使用新的局域网网络状态检测功能
    /// </summary>
    public class NetworkStatusExample : MonoBehaviour
    {
        [Header("网络状态显示")]
        [SerializeField] private bool showNetworkStatus = true;
        [SerializeField] private float statusUpdateInterval = 5f;

        private float _lastStatusUpdate;
        private LocalNetworkStatus.NetworkStatusInfo _currentStatus;

        void Start()
        {
            // 初始化网络状态检测
            Debug.Log("[NetworkStatusExample] Starting network status monitoring...");
        }

        void Update()
        {
            // 定期更新网络状态显示
            if (showNetworkStatus && Time.time - _lastStatusUpdate > statusUpdateInterval)
            {
                UpdateNetworkStatus();
                _lastStatusUpdate = Time.time;
            }
        }

        /// <summary>
        /// 更新网络状态显示
        /// </summary>
        private async void UpdateNetworkStatus()
        {
            try
            {
                // 获取当前网络状态
                _currentStatus = LocalNetworkStatus.Instance.GetCurrentStatus();

                // 输出网络状态信息
                Debug.Log($"[NetworkStatusExample] Network Status: " +
                         $"Quality={_currentStatus.quality}, " +
                         $"Latency={_currentStatus.averageLatency:F1}ms, " +
                         $"Loss={_currentStatus.packetLossRate:F1}%, " +
                         $"Connected={_currentStatus.isConnected}");

                // 获取网络质量建议
                string suggestion = LocalNetworkStatus.Instance.GetQualitySuggestion(_currentStatus.quality);
                Debug.Log($"[NetworkStatusExample] Suggestion: {suggestion}");
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"[NetworkStatusExample] Error updating network status: {ex.Message}");
            }
        }

        /// <summary>
        /// 手动触发网络状态检测
        /// </summary>
        [ContextMenu("Check Network Status")]
        public async void ManualNetworkCheck()
        {
            Debug.Log("[NetworkStatusExample] Starting manual network check...");

            try
            {
                var status = await LocalNetworkStatus.Instance.CheckNetworkStatusAsync(10, 3000);

                Debug.Log($"[NetworkStatusExample] Manual check completed: " +
                         $"Quality={status.quality}, " +
                         $"Latency={status.averageLatency:F1}ms, " +
                         $"Loss={status.packetLossRate:F1}%, " +
                         $"Tests={status.testCount}, " +
                         $"Success={status.successCount}, " +
                         $"Failed={status.failureCount}");
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"[NetworkStatusExample] Manual check failed: {ex.Message}");
            }
        }

        /// <summary>
        /// 快速检查网络连接
        /// </summary>
        [ContextMenu("Quick Connection Check")]
        public async void QuickConnectionCheck()
        {
            Debug.Log("[NetworkStatusExample] Starting quick connection check...");

            try
            {
                bool isConnected = await LocalNetworkStatus.Instance.IsConnectedAsync();
                Debug.Log($"[NetworkStatusExample] Quick check result: {(isConnected ? "Connected" : "Not Connected")}");
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"[NetworkStatusExample] Quick check failed: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取UDP Socket的网络状态（如果存在）
        /// </summary>
        [ContextMenu("Get UDP Socket Network Status")]
        public void GetUdpSocketNetworkStatus()
        {
            // 这里需要根据实际的UDP Socket实例来调用
            // 示例代码，实际使用时需要获取真实的UdpSocket实例
            Debug.Log("[NetworkStatusExample] To get UDP Socket network status, you need to call GetNetworkStatus() on your UdpSocket instance");
        }

        void OnGUI()
        {
            if (!showNetworkStatus || _currentStatus == null) return;

            // 在屏幕上显示网络状态信息
            GUILayout.BeginArea(new Rect(10, 10, 400, 200));
            GUILayout.Label("Network Status Monitor", GUI.skin.box);

            GUILayout.Label($"Quality: {_currentStatus.quality}");
            GUILayout.Label($"Latency: {_currentStatus.averageLatency:F1}ms");
            GUILayout.Label($"Packet Loss: {_currentStatus.packetLossRate:F1}%");
            GUILayout.Label($"Connected: {_currentStatus.isConnected}");
            GUILayout.Label($"Last Check: {_currentStatus.lastChecked:HH:mm:ss}");

            if (GUILayout.Button("Manual Check"))
            {
                ManualNetworkCheck();
            }

            if (GUILayout.Button("Quick Check"))
            {
                QuickConnectionCheck();
            }

            GUILayout.EndArea();
        }
    }
}
